package org.millioncall.yueyoga.common.security;

import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.millioncall.yueyoga.admin.model.Authority;
import org.millioncall.yueyoga.admin.model.Group;
import org.millioncall.yueyoga.admin.model.Role;
import org.millioncall.yueyoga.admin.service.SecurityService;
import org.millioncall.yueyoga.admin.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

public class ZhuwUserDetailsService implements UserDetailsService {
	private UserService userService;
	private SecurityService securityService;

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public SecurityService getSecurityService() {
		return securityService;
	}

	public void setSecurityService(SecurityService securityService) {
		this.securityService = securityService;
	}

	// 取得通过认证的用户对象，到数据库中查询
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException {
		org.millioncall.yueyoga.admin.model.User dbuser = userService
				.getAuthenticateUserByUsername(username);
		Collection<GrantedAuthority> grantedAuths = obtionGrantedAuthorities(dbuser);// 认证用户所拥有的权限，在访问决策器中使用
		boolean enabled = dbuser.isEnabled();// 账号是否启用
		boolean accountNonExpired = !dbuser.isUsernameExpired();// 账号是否未过期
		boolean credentialsNonExpired = !dbuser.isAuthorityExpired();// 权限是否未过期
		boolean accountNonLocked = !dbuser.isLocked();// 账号是否被锁定
		User userdetail = new User(dbuser.getUsername(), dbuser.getPassword(),
				enabled, accountNonExpired, credentialsNonExpired,
				accountNonLocked, grantedAuths);
		return userdetail;
	}

	// 取得认证用户所拥有的权限，到数据库中查询
	private Set<GrantedAuthority> obtionGrantedAuthorities(
			org.millioncall.yueyoga.admin.model.User user) {
		Set<GrantedAuthority> authSet = new HashSet<GrantedAuthority>();// 认证用户所拥有的权限，在访问决策器中用此进行匹配
		List<Group> groups = securityService.getAllGroups(user.getGroups(),
				true);// 取得当前所有已启用的用户组
		Set<Role> roles = securityService.getRolesByGroups(groups, true);// 取得所有已启用的角色
		Set<Authority> authorities = securityService.getAuthoritiesByRoles(
				roles, true);// 取得所有已启用的权限
		for (Authority authority : authorities) {
			authSet.add(new SimpleGrantedAuthority(authority.getName()));
		}
		return authSet;
	}
}